package com.party.web.web.controller.serviceOrder;

import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.model.charge.PackageMember;
import com.party.core.model.charge.ProductPackage;
import com.party.core.model.charge.ProductType;
import com.party.core.model.charge.RemittanceVoucher;
import com.party.core.model.order.PaymentWay;
import com.party.core.model.partner.MemberPartner;
import com.party.core.service.charge.IPackageMemberService;
import com.party.core.service.charge.IPackageService;
import com.party.core.service.charge.IRemittanceVoucherService;
import com.party.core.service.partner.IMemberPartnerService;
import com.party.web.biz.charge.PackageBizService;
import com.party.web.biz.serviceOrder.ServiceOrderBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @program: party
 * @description: 服务订购控制器
 * @author: Hua Qunhao
 * @create: 2019-05-15 09:25
 **/
@Controller
@RequestMapping(value = "serviceOrder")
public class ServiceOrderController {

    @Autowired
    private IPackageService packageService;
    @Autowired
    private IPackageMemberService packageMemberService;
    @Autowired
    private PackageBizService packageBizService;

    @Autowired
    private IRemittanceVoucherService remittanceVoucherService;

    @Autowired
    private ServiceOrderBizService serviceOrderBizService;

    @Autowired
    private IMemberPartnerService memberPartnerService;


    protected static Logger logger = LoggerFactory.getLogger(ServiceOrderController.class);


    /**
     * @Description:服务订购列表
     * @Param: [packageMemberId, type, request]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/5/15
     */
    @RequestMapping(value = "/list")
    public ModelAndView serviceOrderList(CommonInput commonInput, Page page) {
        ModelAndView modelAndView = new ModelAndView("serviceOrder/serviceOrderList");

        String memberId = RealmUtils.getCurrentUser().getId();
        PackageMember packageMember = new PackageMember();
        packageMember.setMemberId(memberId);
        List<PackageMember> packageMembers = packageMemberService.systemBuyList(packageMember, page);

        modelAndView.addObject("list", packageMembers);
        modelAndView.addObject("page", page);
        return modelAndView;
    }

    /**
     * @Description:服务订购详情
     * @Param: [packageMemberId, type, request]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/5/15
     */
    @RequestMapping(value = "/info")
    public ModelAndView serviceOrderInfo(String packageMemberId, Integer type, HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView("serviceOrder/serviceOrderInfo");
        List<ProductPackage> productPackages = null;
        PackageMember packageMember = null;
        String memberId = RealmUtils.getCurrentUser().getId();
        MemberPartner dbMemberPartner = memberPartnerService.findByMemberId(memberId);
        //服务订购列表点击“支付”进来
        if (StringUtils.isNotEmpty(packageMemberId)) {
            packageMember = packageMemberService.get(packageMemberId);
        } else {
            //点击"立即购买"进来，或者切换tab
            type = type == null ? 1 : type;
            ProductPackage querypp = new ProductPackage();
            querypp.setType(ProductType.SYSTEM_TYPE.getCode());
            querypp.setSystemType(type);
            Integer sign = 0;
            //当前系统状态是社群 且 点击是众筹 -------------升级(返回一年的众筹产品)
            if (dbMemberPartner.getSystemType() == ProductPackage.SYSTEM_TYPE_SQ
                    && type == ProductPackage.SYSTEM_TYPE_ZC
            ) {
                sign = 1;
            }
            productPackages = packageService.getGoodslist(querypp, sign);
        }
        modelAndView.addObject("type", type);
        modelAndView.addObject("packageMember", packageMember);
        modelAndView.addObject("productPackages", productPackages);
        return modelAndView;
    }


    /**
     * @Description:确认订购信息
     * @Param: [productId]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019-05-16-0016
     */
    @ResponseBody
    @RequestMapping("/confirmOrder")
    public AjaxResult confirmOrder(String productId) {
        if (StringUtils.isEmpty(productId)) {
            return AjaxResult.error("产品id为空");
        }
        try {
            String memberId = RealmUtils.getCurrentUser().getId();

            ProductPackage productPackage = packageService.get(productId);
            if (null == productPackage || (ProductType.SYSTEM_TYPE.getCode() != productPackage.getType())) {
                return AjaxResult.error("产品类型有误");
            }
            if (serviceOrderBizService.existsDemotion(memberId, productId)) {
                return AjaxResult.error("暂不可购买该套餐，如需购买，请到期后购买或联系客服。");
            }
            if (serviceOrderBizService.isUnpaidOrder(memberId)) {
                return AjaxResult.error("已存在待支付(审核中)的订单，请完成支付(审核通过)或取消订单后再来购买");
            }
            String packageMemberId = packageBizService.saveOrupdatePackageMember(memberId, productPackage);
            return new AjaxResult(true, "确认订购信息成功", packageMemberId, null);
        } catch (Exception e) {
            logger.error("确认订购信息异常", e);
            return AjaxResult.error("确认订购信息失败");
        }
    }

    /**
     * @Description:提交汇款凭证
     * @Param: [remittanceVoucher]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019-05-16-0016
     */
    @ResponseBody
    @RequestMapping("/submitVoucher")
    public AjaxResult submitVoucher(RemittanceVoucher remittanceVoucher, BindingResult result) {
        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            return AjaxResult.error(allErros.get(0).getDefaultMessage());
        }
        try {
            PackageMember packageMember = packageMemberService.get(remittanceVoucher.getPackageMemberId());
            if (null == packageMember) {
                return AjaxResult.error("产品用户关系不存在");
            }
            packageMember.setPayStatus(0);
            packageMember.setPayWay(PaymentWay.COMPANY_PAY.getCode());
            packageMember.setAuditStatus(PackageMember.AUDIT_STATUS_ING);
            packageMemberService.update(packageMember);

            remittanceVoucherService.insert(remittanceVoucher);

            return new AjaxResult(true, "提交汇款凭证成功", remittanceVoucher, null);
        } catch (Exception e) {
            logger.error("提交汇款凭证异常", e);
            return AjaxResult.error("提交汇款凭证失败");
        }
    }

    /**
     * @Description:取消订单
     * @Param: [packageMemberId]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019-05-16-0016
     */
    @ResponseBody
    @RequestMapping("/cancelOrder")
    public AjaxResult cancelOrder(String packageMemberId) {
        if (StringUtils.isEmpty(packageMemberId)) {
            return AjaxResult.error("产品id不能为空");
        }
        try {
            PackageMember packageMember = packageMemberService.get(packageMemberId);
            if (!(PackageMember.AUDIT_STATUS_ING == packageMember.getAuditStatus() ||
                    1 == packageMember.getPayStatus())
            ) {
                return AjaxResult.error("产品状态不正确");
            } else {
                packageMember.setStatus(2);
                packageMemberService.update(packageMember);
                return new AjaxResult(true, "取消订单成功", packageMemberId, null);
            }
        } catch (Exception e) {
            logger.error("取消订单异常", e);
            return AjaxResult.error("取消订单失败");
        }
    }

    /**
     * @Description:是否存在待支付订单
     * @Param:
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019-05-16-0016
     */
    @ResponseBody
    @RequestMapping("/isUnpaidOrder")
    public AjaxResult isUnpaidOrder() {
        try {
            String memberId = RealmUtils.getCurrentUser().getId();
            if (serviceOrderBizService.isUnpaidOrder(memberId)) {
                return AjaxResult.success(true);
            }
        } catch (Exception e) {
            logger.error("查询是否存在待支付订单异常", e);
            return new AjaxResult(false, "查询是否存在待支付订单异常", false, null);
        }
        return AjaxResult.success(false);
    }


    /**
     * @Description:取消订单全部
     * @Param: [packageMemberId]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019-05-16-0016
     */
    @ResponseBody
    @RequestMapping("/cancelOrderAll")
    public AjaxResult cancelOrderAll() {
        try {
            String memberId = RealmUtils.getCurrentUser().getId();
            List<PackageMember> packageMembers = packageMemberService.queryAllUnpaidOrder(memberId);

            for (PackageMember packageMember : packageMembers) {
                packageMember.setStatus(2);
                packageMemberService.update(packageMember);
            }
            return new AjaxResult(true, "取消订单成功");
        } catch (Exception e) {
            logger.error("取消订单异常", e);
            return AjaxResult.error("取消订单失败");
        }
    }

    /**
     * @Description:计算抵扣金额和应付金额
     * @Param:
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019-05-16-0016
     */
    @ResponseBody
    @RequestMapping("/calculateAmount")
    public AjaxResult calculateAmount(String productId) {
        try {
            String memberId = RealmUtils.getCurrentUser().getId();
            PackageMember packageMember = new PackageMember();
            if (serviceOrderBizService.existsDemotion(memberId, productId)) {
                return AjaxResult.error("暂不可购买该套餐，如需购买，请到期后购买或联系客服。");
            }
            packageMember = serviceOrderBizService.getPackageMember(productId, memberId);
            return AjaxResult.success(packageMember);
        } catch (Exception e) {
            logger.error("计算抵扣金额和应付金额异常", e);
            return AjaxResult.error("计算抵扣金额和应付金额失败");
        }
    }
}
